package com.xk.school_device.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xk.school_device.common.Result;
import com.xk.school_device.entity.Assignments;
import com.xk.school_device.entity.Departments;
import com.xk.school_device.entity.Devices;
import com.xk.school_device.entity.Users;
import com.xk.school_device.entity.rep.ReturnDeviceReq;
import com.xk.school_device.mapper.AssignmentsMapper;
import com.xk.school_device.mapper.DepartmentsMapper;
import com.xk.school_device.mapper.DevicesMapper;
import com.xk.school_device.mapper.UsersMapper;
import com.xk.school_device.service.IDevicesService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xk
 * @since 2025-04-16
 */
@RestController
@RequestMapping("/api/devices")
public class DevicesController {

    @Resource
    private IDevicesService devicesService;
    /**
     * 设备登记
     */
    @PostMapping("/register")
    public Result register(@RequestBody Devices devices) {
         devicesService.save(devices);
        return Result.success("设备登记成功");
    }
    /**
     * 设备查询
     */
    @Autowired
    private DepartmentsMapper departmentsMapper;

    @Autowired
    private AssignmentsMapper assignmentsMapper;

    @Autowired
    private UsersMapper userMapper;
    @PostMapping("/query")
    public Result query(@RequestBody Devices devices) {
        // 根据部门id查询设备所属部门
        Departments departments;
        if (devices.getDepartmentId() != null && devices.getDepartmentId().isEmpty()) {
            departments = departmentsMapper.queryById(devices.getDepartmentId());
        } else {
            departments = null;
        }

        QueryWrapper<Devices> queryWrapper = new QueryWrapper<>();
        if (devices.getDeviceId() != null && !devices.getDeviceId().isEmpty()) {
            queryWrapper.eq("device_id", devices.getDeviceId());
        }
        if (devices.getStatus() != null && !devices.getStatus().isEmpty()) {
            queryWrapper.eq("status", devices.getStatus());
        }
        if (devices.getDeviceName() != null && !devices.getDeviceName().isEmpty()) {
            queryWrapper.like("devices_name", devices.getDeviceName());
        }
        if (devices.getModel() != null && !devices.getModel().isEmpty()) {
            queryWrapper.like("model", devices.getModel());
        }
        if (devices.getCategory() != null && !devices.getCategory().isEmpty()) {
            queryWrapper.like("category", devices.getCategory());
        }
        if (devices.getBrand() != null && !devices.getBrand().isEmpty()) {
            queryWrapper.like("brand", devices.getBrand());
        }
        if (devices.getSerialNumber() != null && !devices.getSerialNumber().isEmpty()) {
            queryWrapper.like("serial_number", devices.getSerialNumber());
        }

        List<Devices> devices1 = devicesService.list(queryWrapper);
        if (departments != null) {
            devices1.forEach(device -> device.setDepartmentName(departments.getDepartmentName()));
        }
        for (Devices device : devices1) {
            Assignments userName = assignmentsMapper.getUserName(device.getDeviceId());
            if (userName != null) {
            if(userName.getAssignType().equals("user")){
                device.setUseType("个人申请");
                Users users=userMapper.getUserById(userName.getAssignedTo());
                device.setUserName(users.getFullName());
            } else {
                device.setUseType("部门申请");
                Departments d = departmentsMapper.queryById(userName.getDepartmentId());
                device.setUseDepartmentName(d.getDepartmentName());
            }
            }
        }
        return Result.success("设备查询成功", devices1);
    }


    @PostMapping("/queryInUse")
    public Result queryInUse(@RequestBody Devices devices) {
        // 根据部门id查询设备所属部门
        Departments departments;
        if (devices.getDepartmentId() != null && devices.getDepartmentId().isEmpty()) {
            departments = departmentsMapper.queryById(devices.getDepartmentId());
        } else {
            departments = null;
        }

        QueryWrapper<Devices> queryWrapper = new QueryWrapper<>();
        if (devices.getDeviceId() != null && !devices.getDeviceId().isEmpty()) {
            queryWrapper.eq("device_id", devices.getDeviceId());
        }

            queryWrapper.eq("status", "in_use");

        if (devices.getDeviceName() != null && !devices.getDeviceName().isEmpty()) {
            queryWrapper.like("devices_name", devices.getDeviceName());
        }
        if (devices.getModel() != null && !devices.getModel().isEmpty()) {
            queryWrapper.like("model", devices.getModel());
        }
        if (devices.getCategory() != null && !devices.getCategory().isEmpty()) {
            queryWrapper.like("category", devices.getCategory());
        }
        if (devices.getBrand() != null && !devices.getBrand().isEmpty()) {
            queryWrapper.like("brand", devices.getBrand());
        }
        if (devices.getSerialNumber() != null && !devices.getSerialNumber().isEmpty()) {
            queryWrapper.like("serial_number", devices.getSerialNumber());
        }

        List<Devices> devices1 = devicesService.list(queryWrapper);
        if (departments != null) {
            devices1.forEach(device -> device.setDepartmentName(departments.getDepartmentName()));
        }
        for (Devices device : devices1) {
            Assignments userName = assignmentsMapper.getUserName(device.getDeviceId());
            if (userName != null) {
                if(userName.getAssignType().equals("user")){
                    device.setUseType("个人申请");
                    Users users=userMapper.getUserById(userName.getAssignedTo());
                    device.setUserName(users.getFullName());
                } else {
                    device.setUseType("部门申请");
                    Departments d = departmentsMapper.queryById(userName.getDepartmentId());
                    device.setUseDepartmentName(d.getDepartmentName());
                }
            }
        }
        return Result.success("设备查询成功", devices1);
    }
    /**
     * 设备更新
     */
    private static final Logger logger = LoggerFactory.getLogger(DevicesController.class);

    @PostMapping("/update")
    public Result update(@RequestBody Devices devices) {
          devicesService.updateDevices(devices);
      return Result.success("设备更新成功");
    }
    /**
     * 设备删除
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Devices devices) {
        devicesService.deleteDevice(devices);
        return Result.success("设备删除成功");
    }

    @Autowired
    private DevicesMapper devicesMapper;
    @PostMapping("return")
    public Result returnDevice(@RequestBody ReturnDeviceReq returnDeviceReq) {
        Devices deviceById = devicesMapper.getDeviceById(returnDeviceReq.getDeviceId());

        // 检查设备状态是否为使用中，只有使用中的设备才能归还
        if (!deviceById.getStatus().equals("in_use")) {
            return Result.failure("设备当前状态不支持归还");
        }
        // 设置设备状态为库存中
        deviceById.setStatus("in_stock");

        // 更新设备状态
        devicesMapper.updateDeviceStatus(deviceById);

        // 更新设备分配记录状态
        assignmentsMapper.updateAssignmentStatusByDeviceId(returnDeviceReq.getDeviceId(), "returned");

        return Result.success("设备归还成功");
    }
}
